package com.logisticsrepair.config;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.filter.SaServletFilter;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import com.logisticsrepair.util.HandlerException.HandlerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;
import java.util.ArrayList;

@Configuration
public class SaTokenConfigure implements WebMvcConfigurer {

    @Autowired
    HandlerException handlerException;

    static final ArrayList<String> excludePattern = new ArrayList<>();
    static final ArrayList<String> userHomeExcludePath = new ArrayList<>();
    static final ArrayList<String> workerHomeExcludePath = new ArrayList<>();

    static {
        excludePattern.add("/wx/**");
        excludePattern.add("/socket/login/{socketID}");
        excludePattern.add("/socket/pay/{socketID}");
        excludePattern.add("/workerHome/codeCheck");
        excludePattern.add("/PaymentScanCode/**");
        excludePattern.add("/uploadImg/**");

        userHomeExcludePath.add("/userHome/repairStatus");
        userHomeExcludePath.add("/userHome/repairType");
        userHomeExcludePath.add("/userHome/pullAllAnnouncement");

        workerHomeExcludePath.add("/workerHome/codeCheck");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        File dest = new File("src/main/resources/static/uploadImg");
        //windows、linux通用
        registry.addResourceHandler("/uploadImg/**").addResourceLocations("file:" + dest.getAbsolutePath() + "/");
    }

    /**
     * 全局过滤器
     *
     * @return
     */
    @Bean
    public SaServletFilter saServletFilter() {
        SaServletFilter saServletFilter = new SaServletFilter();

        // 指定 拦截路由 与 放行路由
        saServletFilter.addInclude("/**");
        saServletFilter.addExclude("/favicon.ico");

        // 认证函数: 每次请求执行
        saServletFilter.setAuth(authRun -> {
            String satoken = SaHolder.getRequest().getHeader("satoken");
            System.out.println("\033[34;4m" + "---------- 进入Sa-Token全局认证 -----------" + "\033[0;0m");
            System.out.println("satoken: " + satoken);

            //登录认证 -- 拦截所有路由，并排除 指定地址 用于开放登录
            SaRouter.match("/**")
                    .notMatch(excludePattern)
                    .check(r -> {
                        try {
                            StpUtil.checkLogin();
                        } catch (NotLoginException nle) {
                            r.back(handlerException.handlerNotLogin(nle));
                        }
                    });

            SaRouter.match("/userHome/**").notMatch(userHomeExcludePath).check(r -> {
                try {
                    StpUtil.checkRole("user");
                    StpUtil.checkPermission("user");
                } catch (Exception e) {
                    r.back(handlerException.handlerRolePermission(e));
                }
            });

            SaRouter.match("/workerHome/**").notMatch(workerHomeExcludePath).check(r -> {
                try {
                    StpUtil.checkRole("worker");
                    StpUtil.checkPermission("worker");
                } catch (Exception e) {
                    r.back(handlerException.handlerRolePermission(e));
                }
            });

        });

        // 前置函数：在每次认证函数之前执行
        saServletFilter.setBeforeAuth(run -> {
            // 查看跨域请求的地址
            //System.out.println(SaHolder.getRequest().getHeader("Origin"));
            // ---------- 设置跨域响应头 ----------
            SaHolder.getResponse()
                    // 允许指定域访问跨域资源
                    .setHeader("Access-Control-Allow-Origin", "http://localhost:3000")
                    // 允许所有请求方式
                    .setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE")
                    // 有效时间
                    .setHeader("Access-Control-Max-Age", "3600")
                    // 允许的header参数
                    .setHeader("Access-Control-Allow-Headers", "*");
        });
        return saServletFilter;
    }
}
